package org.qhhc.thread.synchronizedStudy.SynTest;

public class SynTest {
    private static int sharedCounter = 0;
    private final Object lock = new Object();

    // 同步方法：锁是当前实例对象（若静态则为类锁）
    public synchronized void incrementByMethod() {
        sharedCounter++;
    }

    // 同步代码块：显式指定锁对象
    public void incrementByBlock() {
        synchronized (lock) {
            sharedCounter++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SynTest synTest = new SynTest();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                synTest.incrementByMethod();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                synTest.incrementByBlock();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Final counter: " + sharedCounter); // 预期结果 2000
    }
}